<template>
  <div>
    <InfoTable
      title="账单信息"
      :data="bills"
      :columns="columns"
      :pagination="pagination"
      key-field="id"
      search-placeholder="请输入手机号或虚拟号"
      create-button-text="创建账单"
      :selected-items="selectedBills"
      @search="handleSearch"
      @create="handleCreate"
      @action="handleAction"
      @page-change="handlePageChange"
      @batch-delete="handleBatchDelete"
      @toggle-item-selection="toggleBillSelection"
      @toggle-select-all="toggleSelectAll"
      @clear-selection="clearSelection"
    >
      <template #advanced-search>
        <div class="advanced-search">
          <button @click="toggleAdvancedSearch" class="advanced-search-toggle">
            {{ showAdvancedSearch ? '收起' : '高级搜索' }}
          </button>
          <div v-if="showAdvancedSearch" class="advanced-search-form">
            <div class="form-row">
              <label>时间范围：</label>
              <input type="date" v-model="startDate" /> 至
              <input type="date" v-model="endDate" />
            </div>
            <div class="form-row">
              <label>账单状态：</label>
              <select v-model="billStatus">
                <option value="">全部</option>
                <option value="paid">已支付</option>
                <option value="unpaid">未支付</option>
                <option value="overdue">已逾期</option>
              </select>
            </div>
            <button @click="handleAdvancedSearch" class="search-button">高级搜索</button>
          </div>
        </div>
      </template>
      
      <template #column-call_duration="{ item }">
        {{ formatDuration(item.call_duration) }}
      </template>
      
      <template #column-total_fee="{ item }">
        {{ formatFee(item.total_fee) }}
      </template>
      
      <template #column-virtual_fee="{ item }">
        {{ formatFee(item.virtual_fee) }}
      </template>
      
      <template #column-create_time="{ item }">
        {{ formatDate(item.create_time) }}
      </template>
      
      <template #column-status="{ item }">
        <span :class="['status', item.status]">{{ getStatusText(item.status) }}</span>
      </template>
    </InfoTable>
    
    <!-- 创建账单弹窗 -->
    <CreateBill 
      :visible="showCreateDialog"
      @update:visible="showCreateDialog = $event"
      @success="handleCreateSuccess"
    />
    
    <!-- 编辑账单弹窗 -->
    <EditBill 
      :visible="showEditDialog"
      :bill-id="currentEditBillId"
      @update:visible="showEditDialog = $event"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script>
import InfoTable from '@/components/InfoTable.vue'
import CreateBill from './CreateBill.vue'
import EditBill from './EditBill.vue'
import { ElMessage } from 'element-plus'
import { getBillInfo, deleteBillInfo, deleteBatchBillInfo } from '@/apis/billInfo'

export default {
  name: 'BillInfoTemplate',
  components: {
    InfoTable,
    CreateBill,
    EditBill
  },
  data() {
    return {
      showAdvancedSearch: false,
      startDate: '',
      endDate: '',
      billStatus: '',
      bills: [],
      selectedBills: [],
      showCreateDialog: false,
      showEditDialog: false,
      currentEditBillId: null,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      columns: [
        { key: 'id', title: '账单ID' },
        { key: 'callerPhone', title: '主叫手机号' },
        { key: 'calleePhone', title: '被叫手机号' },
        { key: 'virtualNumber', title: '虚拟号' },
        { key: 'callDuration', title: '通话时长(秒)' },
        { key: 'totalFee', title: '总费用(元)' },
        { key: 'virtualFee', title: '服务费(元)' },
        { key: 'createTime', title: '生成时间' },
        { key: 'updateTime', title: '更新时间' }
      ],
      loading: false
    }
  },
  async mounted() {
    await this.fetchBillData()
  },
  methods: {
    // 获取账单数据
    async fetchBillData(queryParams = {}) {
      this.loading = true
      try {
        const params = {
          offset: (this.pagination.current - 1) * this.pagination.pageSize,
          limit: this.pagination.pageSize,
          ...queryParams
        }
        
        const res = await getBillInfo(params)
        // 添加对响应的检查，避免读取undefined的属性
        if (res && res.code === 0) {
          this.bills = res.data?.list || res.data || []
          this.pagination.total = res.data?.total || this.bills.length
        } else {
          ElMessage.error(res?.msg || '获取账单数据失败')
          // 发生错误时确保数据清空或者保持现状
          this.bills = []
        }
      } catch (error) {
        console.error('获取账单数据异常:', error)
        ElMessage.error('获取账单数据异常: ' + (error.message || '未知错误'))
        // 网络错误时确保数据清空或者保持现状
        this.bills = []
      } finally {
        this.loading = false
      }
    },
    
    handleSearch(query) {
      const searchParams = query ? { keyword: query } : {}
      this.pagination.current = 1
      this.fetchBillData(searchParams)
    },
    
    handleCreate() {
      this.showCreateDialog = true
    },
    
    handleCreateSuccess() {
      // 创建成功后刷新数据
      this.fetchBillData()
    },
    
    handleEditSuccess() {
      // 编辑成功后刷新数据
      this.fetchBillData()
      this.currentEditBillId = null
    },
    
    async handleAction({ action, item }) {
      switch (action) {
        case 'view':
          console.log('查看账单:', item)
          break
        case 'edit':
          this.currentEditBillId = item.id
          this.showEditDialog = true
          break
        case 'delete':
          try {
            const res = await deleteBillInfo(item.id)
            // 添加对响应的检查
            if (res && res.code === 0) {
              ElMessage.success('删除成功')
              // 重新获取数据
              this.fetchBillData()
              // 从选中项中移除
              const index = this.selectedBills.indexOf(item.id);
              if (index > -1) {
                this.selectedBills.splice(index, 1);
              }
            } else {
              ElMessage.error(res?.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除账单异常:', error)
            ElMessage.error('删除账单异常: ' + (error.message || '未知错误'))
          }
          break
      }
    },
    
    handlePageChange(page) {
      this.pagination.current = page
      this.fetchBillData()
      // 清除选中项
      this.clearSelection();
    },
    
    toggleAdvancedSearch() {
      this.showAdvancedSearch = !this.showAdvancedSearch
    },
    
    handleAdvancedSearch() {
      const advancedParams = {
        startDate: this.startDate,
        endDate: this.endDate,
        status: this.billStatus
      }
      this.pagination.current = 1
      this.fetchBillData(advancedParams)
    },
    
    getStatusText(status) {
      const statusMap = {
        'paid': '已支付',
        'unpaid': '未支付',
        'overdue': '已逾期'
      }
      return statusMap[status] || '未知'
    },
    
    // 格式化通话时长（秒转为 MM:SS 格式）
    formatDuration(seconds) {
      if (!seconds) return '0'
      const mins = Math.floor(seconds / 60)
      const secs = seconds % 60
      if (mins > 0) {
        return `${mins}分${secs}秒`
      }
      return `${secs}`
    },
    
    // 格式化费用（分转为元）
    formatFee(fee) {
      if (fee === undefined || fee === null) return '0.00'
      return (fee / 100).toFixed(2)
    },
    
    // 格式化日期
    formatDate(date) {
      // 直接返回数据库中的时间格式，不进行额外转换
      return date || '';
    },
    
    // 处理批量删除
    async handleBatchDelete(selectedItems) {
      if (!selectedItems.length) {
        ElMessage.warning('请选择要删除的账单')
        return
      }
      
      try {
        const ids = selectedItems.join(',')
        const res = await deleteBatchBillInfo(ids)
        // 添加对响应的检查
        if (res && res.code === 0) {
          ElMessage.success('批量删除成功')
          // 重新获取数据
          this.fetchBillData()
          // 清除选中项
          this.selectedBills = [];
        } else {
          ElMessage.error(res?.msg || '批量删除失败')
        }
      } catch (error) {
        console.error('批量删除账单异常:', error)
        ElMessage.error('批量删除账单异常: ' + (error.message || '未知错误'))
      }
    },
    
    // 切换账单选择状态
    toggleBillSelection(billId) {
      const index = this.selectedBills.indexOf(billId);
      if (index > -1) {
        // 如果已选中，则取消选中
        this.selectedBills.splice(index, 1);
      } else {
        // 如果未选中，则添加到选中列表
        this.selectedBills.push(billId);
      }
    },
    
    // 切换全选状态
    toggleSelectAll() {
      if (this.selectedBills.length === this.bills.length) {
        // 如果已全选，则取消全选
        this.selectedBills = [];
      } else {
        // 如果未全选，则全选当前页的所有项目
        this.selectedBills = this.bills.map(bill => bill.id);
      }
    },
    
    // 清除选中项
    clearSelection() {
      this.selectedBills = [];
    }
  },
  watch: {
    bills() {
      // 数据变化时清除选中项中已不存在的项
      this.selectedBills = this.selectedBills.filter(billId => 
        this.bills.some(bill => bill.id === billId)
      );
    }
  }
}
</script>

<style scoped>
.form-row {
  margin: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-row label {
  width: 80px;
  font-weight: bold;
}

.form-row input,
.form-row select {
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.advanced-search {
  margin-top: 15px;
}

.advanced-search-toggle {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.advanced-search-toggle:hover {
  background-color: #5a6268;
}

.advanced-search-form {
  margin-top: 15px;
  padding: 15px;
  background-color: #e9ecef;
  border-radius: 4px;
}

.status.paid {
  background-color: #28a745;
  color: white;
}

.status.unpaid {
  background-color: #ffc107;
  color: #212529;
}

.status.overdue {
  background-color: #dc3545;
  color: white;
}
</style>